"use client"

import { useState, useEffect, useCallback } from "react"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import { Search, Star, X, Plus } from "lucide-react"
import { api, useApiCall } from "@/lib/api"
import { Stock } from "@/lib/api/stocks"
import { useWatch } from "@/lib/hooks/use-watch"
import { useToast } from "@/hooks/use-toast"

interface StockSearchDialogProps {
  children?: React.ReactNode
  onStockAdded?: (stockCode: string) => void
}

/**
 * 股票搜索对话框组件
 * 允许用户搜索全量股票列表并快速关注
 */
export function StockSearchDialog({ children, onStockAdded }: StockSearchDialogProps) {
  const [open, setOpen] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState("")
  const [searchResults, setSearchResults] = useState<Stock[]>([])
  const watchHook = useWatch()
  const { toast } = useToast()

  // 搜索股票API调用
  const { execute: searchStocks, isLoading: isSearching } = useApiCall(
    api.stocks.searchStocks,
    {
      showToast: false,
      onSuccess: (data) => {
        setSearchResults(data || [])
        if (!data || data.length === 0) {
          toast({
            title: "未找到股票",
            description: "请尝试使用其他关键词搜索",
            variant: "default",
            duration: 3000,
          })
        }
      },
      onError: (error) => {
        toast({
          title: "搜索失败",
          description: error.message || "无法搜索股票，请稍后重试",
          variant: "destructive",
          duration: 3000,
        })
        setSearchResults([])
      },
    }
  )

  // 防抖搜索
  const handleSearch = useCallback(() => {
    const keyword = searchKeyword.trim()
    if (!keyword) {
      setSearchResults([])
      return
    }

    if (keyword.length < 2) {
      toast({
        title: "搜索关键词太短",
        description: "请输入至少2个字符进行搜索",
        variant: "default",
        duration: 2000,
      })
      return
    }

    searchStocks(keyword)
  }, [searchKeyword, searchStocks, toast])

  // 按Enter键搜索
  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      handleSearch()
    }
  }

  // 清空搜索
  const handleClearSearch = () => {
    setSearchKeyword("")
    setSearchResults([])
  }

  // 关注股票
  const handleToggleWatch = async (stock: Stock) => {
    try {
      await watchHook.toggle(stock.code)
      if (!watchHook.isWatched(stock.code)) {
        onStockAdded?.(stock.code)
        toast({
          title: "关注成功",
          description: `已关注 ${stock.name} (${stock.code})`,
          duration: 2000,
        })
      }
    } catch (error: any) {
      // useApiCall已经处理了错误提示
    }
  }

  // 关闭对话框时清空搜索
  useEffect(() => {
    if (!open) {
      handleClearSearch()
    }
  }, [open])

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {children || (
          <Button variant="outline" className="flex items-center space-x-2">
            <Plus className="w-4 h-4" />
            <span>添加关注</span>
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="max-w-3xl max-h-[80vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="text-xl font-bold">搜索股票</DialogTitle>
          <DialogDescription>
            搜索并关注您感兴趣的股票
          </DialogDescription>
        </DialogHeader>

        {/* 搜索框 */}
        <div className="flex items-center space-x-2 py-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="输入股票代码或名称"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onKeyPress={handleKeyPress}
              className="pl-10 pr-10"
              autoFocus
            />
            {searchKeyword && (
              <Button
                variant="ghost"
                size="sm"
                onClick={handleClearSearch}
                className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 p-0"
              >
                <X className="w-4 h-4" />
              </Button>
            )}
          </div>
          <Button onClick={handleSearch} disabled={isSearching || !searchKeyword.trim()}>
            {isSearching ? "搜索中..." : "搜索"}
          </Button>
        </div>

        {/* 搜索结果 */}
        <div className="flex-1 overflow-y-auto pr-2">
          {isSearching ? (
            <div className="space-y-3">
              {Array.from({ length: 5 }).map((_, i) => (
                <StockSearchItemSkeleton key={i} />
              ))}
            </div>
          ) : searchResults.length > 0 ? (
            <div className="space-y-3">
              {searchResults.map((stock) => (
                <StockSearchItem
                  key={stock.code}
                  stock={stock}
                  isWatched={watchHook.isWatched(stock.code)}
                  isToggling={watchHook.isToggling}
                  onToggleWatch={handleToggleWatch}
                />
              ))}
            </div>
          ) : searchKeyword ? (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <Search className="w-16 h-16 text-muted-foreground/40 mb-4" />
              <p className="text-muted-foreground">未找到相关股票</p>
              <p className="text-sm text-muted-foreground/80 mt-2">
                请尝试使用其他关键词搜索
              </p>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <Search className="w-16 h-16 text-muted-foreground/40 mb-4" />
              <p className="text-muted-foreground">输入股票代码或名称开始搜索</p>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}

/**
 * 股票搜索结果项
 */
interface StockSearchItemProps {
  stock: Stock
  isWatched: boolean
  isToggling: boolean
  onToggleWatch: (stock: Stock) => void
}

function StockSearchItem({ stock, isWatched, isToggling, onToggleWatch }: StockSearchItemProps) {
  return (
    <Card className="hover:shadow-md transition-shadow">
      <CardContent className="p-4">
        <div className="flex items-center justify-between">
          {/* 股票信息 */}
          <div className="flex-1">
            <div className="flex items-center space-x-3 mb-2">
              <div>
                <h3 className="font-semibold text-base">{stock.name}</h3>
                <div className="flex items-center space-x-2 mt-1">
                  <p className="text-sm text-muted-foreground">{stock.code}</p>
                  {stock.exchange && (
                    <Badge variant="outline" className="text-xs">
                      {stock.exchange === "SH" ? "上交所" : stock.exchange === "SZ" ? "深交所" : stock.exchange}
                    </Badge>
                  )}
                  {stock.industry && (
                    <Badge variant="secondary" className="text-xs">
                      {stock.industry}
                    </Badge>
                  )}
                  {stock.stockType && (
                    <Badge variant="outline" className="text-xs">
                      {stock.stockType}
                    </Badge>
                  )}
                </div>
              </div>
            </div>

            {/* 状态信息 */}
            <div className="flex items-center space-x-4 text-sm">
              {stock.isSuspended && (
                <Badge variant="destructive" className="text-xs">
                  停牌
                </Badge>
              )}
              {stock.isTradable === false && (
                <Badge variant="secondary" className="text-xs">
                  不可交易
                </Badge>
              )}
              {stock.isTradable && !stock.isSuspended && (
                <span className="text-xs text-muted-foreground">可交易</span>
              )}
            </div>
          </div>

          {/* 关注按钮 */}
          <Button
            variant="ghost"
            size="sm"
            className="h-8 w-8 p-0 ml-4"
            onClick={() => onToggleWatch(stock)}
            disabled={isToggling || stock.isSuspended || !stock.isTradable}
          >
            <Star
              className={`w-5 h-5 ${isWatched ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground"
                }`}
            />
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 加载骨架屏
 */
function StockSearchItemSkeleton() {
  return (
    <Card>
      <CardContent className="p-4">
        <div className="flex items-center justify-between">
          <div className="flex-1 space-y-3">
            <div className="space-y-2">
              <Skeleton className="h-5 w-32" />
              <div className="flex items-center space-x-2">
                <Skeleton className="h-4 w-16" />
                <Skeleton className="h-4 w-12" />
                <Skeleton className="h-4 w-16" />
              </div>
            </div>
            <div className="flex items-center space-x-4">
              <Skeleton className="h-4 w-24" />
              <Skeleton className="h-4 w-16" />
              <Skeleton className="h-4 w-20" />
            </div>
          </div>
          <Skeleton className="h-9 w-20 ml-4" />
        </div>
      </CardContent>
    </Card>
  )
}

